﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;

namespace Krile.Forms.ConfigForm.Children
{
    public partial class Network : Krilib.Control.ConfigPage
    {
        public Network()
        {
            InitializeComponent();
        }

        private void Network_Load(object sender, EventArgs e)
        {
            wpCustomGroup.Enabled = false;
            if (Core.Config.Network.WebProxy == null)
                WebProxy_No.Checked = true;
            else if (Core.Config.Network.WebProxy == WebRequest.DefaultWebProxy)
                WebProxy_Default.Checked = true;
            else
            {
                WebProxy_Custom.Checked = true;
                wpCustomGroup.Enabled = true;
                WPAddrPort.Text = ((WebProxy)Core.Config.Network.WebProxy).Address.OriginalString;
                WPBypasslist.Text = String.Join(" ", ((WebProxy)Core.Config.Network.WebProxy).BypassList);
                WPBypassOnLocal.Checked = ((WebProxy)Core.Config.Network.WebProxy).BypassProxyOnLocal;
            }
            Timeout.Value = Core.Config.Network.Timeout;
            ImgParallelDlMax.Value = Core.Config.Network.ImgParallelDlMax;
            UseGZipCompression.Checked = Core.Config.Network.UseGZipCompression;
            BrowserPath.Text = Core.Config.Network.BrowserPath;
        }

        public override void Apply()
        {
            if (WebProxy_No.Checked)
                Core.Config.Network.WebProxy = null;
            else if (WebProxy_Default.Checked)
                Core.Config.Network.WebProxy = WebRequest.DefaultWebProxy;
            else
            {
                Core.Config.Network.WebProxy = new WebProxy(
                    WPAddrPort.Text,
                    WPBypassOnLocal.Checked,
                    WPBypasslist.Text.Split(' '));
            }
            Core.Config.Network.Timeout = (int)Timeout.Value;
            Core.Config.Network.ImgParallelDlMax = (int)ImgParallelDlMax.Value;
            Core.Config.Network.UseGZipCompression = UseGZipCompression.Checked;
            Core.Config.Network.BrowserPath = BrowserPath.Text;
        }

        private void WebProxy_Custom_CheckedChanged(object sender, EventArgs e)
        {
            wpCustomGroup.Enabled = WebProxy_Custom.Checked;
        }

        private void OpenBrowser_Click(object sender, EventArgs e)
        {
            using (var fd = new OpenFileDialog())
            {
                fd.Filter = "Executables|*.exe";
                fd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
                if (fd.ShowDialog() == DialogResult.OK)
                {
                    BrowserPath.Text = fd.FileName;
                }
            }
        }
    }
}
